<template>
  <div>
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="用户名" prop="username">
        <el-input type="text" v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="ruleForm.password" show-password></el-input>
      </el-form-item>
  
      <el-form-item label="验证码" prop="code">
        <el-input v-model="ruleForm.code" placeholder="请输入验证码" maxlength="4" style="width: 180px;float: left;"></el-input>
  
        <div class="Verification" @click="clickVerification"  style="float: right;">
          <img :src="VerificationImg" style="height:40px;width:110px;"/>
        </div>
  
      </el-form-item>
  
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')" :loading="loginLoading"  style="float: left;">
          <span>{{ loginBtn }}</span>
        </el-button>
        <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "userLogin",
  data() {
    return {
      ruleForm: {
        username: 'test',
        password: 'test123456',
        code: "",
        time: ""
      },
      VerificationImg: "",
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 2, max: 18, message: '长度在 2 到 18 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 18, message: '长度在 5 到 18 个字符', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { min: 4, max: 4, message: '请输入正确的验证码', trigger: 'blur' }
        ]
      },
      loginBtn: '登录',
      loginLoading: false,
    };
  },
  mounted() {
    this.clickVerification()
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        let then = this
        if (valid) {
          this.loginBtn = "登陆中..."
          this.loginLoading = true
          this.$axios.post("/login", this.ruleForm).then(res => {
            this.$store.commit("SET_USERINFO", res.data.data.teacher)
            this.$store.commit("SET_TOKEN", res.data.data.token)
            this.$router.replace("/")
          }).catch(()=> {
            //总会执行
            then.loginLoading = false
            then.loginBtn = '登录'
            this.clickVerification()
          })
        } else {
          return false;
        }
      });
    },
    clickVerification() {
      this.ruleForm.time = Date.now()
      this.VerificationImg = "/apis/code?time=" + this.ruleForm.time
    }
    // resetForm(formName) {
    //   this.$refs[formName].resetFields();
    // }
  }
}
</script>

<style>
.demo-ruleForm {
  width: 400px;
  margin: 300px auto;
  text-align: center;
}
</style>